﻿using System;
using System.Text;

namespace EasyIot.WinApp
{
    class DataHelper
    {
        static DateTime dtStart = new DateTime(1970, 1, 1);

        /// <summary>
        /// 将byte[]转换为相对应的字符串,0xae00cf => "AE00CF"
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string ToHexString(byte[] bytes, int length, bool space)
        {
            string strFill = space ? " " : "";
            string hexString = string.Empty;
            if (bytes != null)
            {
                StringBuilder strB = new StringBuilder();

                for (int i = 0; i < length; i++)
                {
                    strB.Append(bytes[i].ToString("X2") + strFill);
                }
                hexString = strB.ToString();
            }

            hexString = hexString.Trim();

            return hexString;
        }

        /// <summary>
        /// 时间戳
        /// </summary>
        /// <returns></returns>
        public static int GetNowTimestamp()
        { 
            return (int)(DateTime.Now - dtStart).TotalSeconds;
        }

        public static int String2Int(string val)
        {
            int ret = 0;
            try { ret = Convert.ToInt32(val); } catch (Exception ex) { LogHelper.AppendLog("[Error] <DataHelper-String2Int>,errmsg:" + ex.Message); }
            return ret;
        }

        /// <summary>
        /// 字节数组转字符串
        /// </summary>
        /// <param name="_byValue"></param>
        /// <returns></returns>
        public static string ByteToString(byte[] _byValue)
        {
            string sResult = Encoding.GetEncoding("GB2312").GetString(_byValue).Replace("\0", string.Empty).Trim();
            return sResult;
        }

        public static int GetLength(string str)
        {
            if (str == null || str.Length == 0) { return 0; }

            int l = str.Length;
            int realLen = l;

            int clen = 0;//当前长度
            while (clen < l)
            {
                //每遇到一个中文，则将实际长度加一。
                if ((int)str[clen] > 128) { realLen++; }
                clen++;
            }

            return realLen;
        }

        /// <summary>
        /// 数字加0补齐
        /// </summary>
        /// <param name="iVal"></param>
        /// <param name="iPadLen"></param>
        /// <returns></returns>
        public static string Lpad(int iVal, int iPadLen)
        {
            return iVal.ToString().PadLeft(iPadLen, '0');
        }

        /// <summary>
        /// 字符串转字节数组
        /// </summary>
        /// <param name="buf"></param>
        /// <returns></returns>
        public static byte[] StringToByte(string str)
        {
            if (string.IsNullOrEmpty(str)) str = string.Empty;
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            return Encoding.GetEncoding("GB2312").GetBytes(str);
        }
    }
}